//
//  SLSetBoatViewController.m
//  StarLight
//
//  Created by 吴涛 on 16/6/4.
//  Copyright © 2016年 Duke.Wu. All rights reserved.
//

#import "SLSetBoatViewController.h"
#import "SLLabelFeild.h"
#import "SLNetWork.h"
#import "STPopup.h"
#import "SLPackageOrBoatTypeViewController.h"
#import "SLNearlyBoatDetailViewModel.h"




@interface SLSetBoatViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
/**船名*/
@property (nonatomic, strong) SLLabelFeild *boatNameLF;
/**呼号*/
@property (nonatomic, strong) SLLabelFeild *mmsiLF;
/**船舶类型*/
@property (nonatomic, strong) SLLabelFeild *boatTypeLF;
/**船载重*/
@property (nonatomic, strong) SLLabelFeild *weightLF;
/**船吃水*/
@property (nonatomic, strong) SLLabelFeild *draftLF;
/**船宽*/
@property (nonatomic, strong) SLLabelFeild *widthLF;
/**船长*/
@property (nonatomic, strong) SLLabelFeild *longLF;
/**备注*/
@property (nonatomic, strong) SLLabelFeild *noteLF;

@property (nonatomic, strong) UIButton *addImageBtn;

@property (nonatomic, strong) UIView *contentView;

@property (nonatomic, strong) UIScrollView *mainScrollView;

@property (nonatomic, strong) UIView *addView;

@property (nonatomic, strong) UIButton *confirmBtn;

@property (nonatomic, strong) UIButton *fontBtn;

@property (nonatomic, strong) UIButton *beforBtn;

@property (nonatomic, strong) UIButton *button;


@property (nonatomic, strong) SLBoatsDetailModel *detailModel;


@end


@implementation SLSetBoatViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  [self setUpUI];
  [self addConstrains];
}

- (void)viewWillAppear:(BOOL)animated{
  [super viewWillAppear:animated];
  [self.navigationController setNavigationBarHidden:NO animated:YES];
  self.view.backgroundColor = [UIColor defeutBackgroudColor];
  self.title = @"船舶详情";
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)delectBoat{
  NSString *postUrl = [NSString backUrlWithService:@"boat" methodName:@"delboat"];
  NSDictionary *para = @{@"bid":self.detailModel.bid,@"uid":[DEFAULTS objectForKey:loginInfo][@"id"]};
  
  @weakify(self)
  [SLNetWork postDataWithParameters:para postUrl:postUrl complete:^(id respond, NSError *error) {
    @strongify(self)
    if (!error) {
      [[NSNotificationCenter defaultCenter] postNotificationName:kSetBoatsDismiss object:nil];
      [self.navigationController popViewControllerAnimated:YES];
    }

  }];
  
}


- (void)showWithBid:(NSString *)bid{
  @weakify(self)
  NSString *url = [NSString stringWithFormat:@"%@/boat/boatinfo?bid=%@",baseUrl,bid];
  [SLNetWork getDataWithRequest:url complete:^(id respond, NSError *error) {
    @strongify(self)
    if (!error) {
      SLBoatsDetailModel *model = [SLBoatsDetailModel mj_objectWithKeyValues:respond[@"data"]];
      self.detailModel = model;
      self.boatNameLF.contentField.text = model.boatname;
      self.mmsiLF.contentField.text = model.mmsi;
      self.boatTypeLF.contentField.text = model.boattype;
      self.weightLF.contentField.text = [NSString stringWithFormat:@"%ld",(long)model.loads];
      self.draftLF.contentField.text = [NSString stringWithFormat:@"%ld",(long)model.draft];
      self.longLF.contentField.text = [NSString stringWithFormat:@"%ld",(long)model.height];
      self.widthLF.contentField.text = [NSString stringWithFormat:@"%ld",(long)model.weight];
      self.noteLF.contentField.text = model.note;
      [self.addImageBtn sd_setImageWithURL:[NSURL URLWithString:model.image] forState:UIControlStateNormal];
      if (model.cockpit == 1) {
        self.fontBtn.selected = YES;
      }else{
        self.beforBtn.selected = YES;
      }
    }
  }];
}


#pragma mark - Private Methods

- (void)endEdited{
  [self.view endEditing:YES];
}

- (void)selectBoatType{
  SLPackageOrBoatTypeViewController *boatTypeVC = [[SLPackageOrBoatTypeViewController alloc] initWithType:PackageOrBoatTypeBoat];
  STPopupController *popVC = [[STPopupController alloc] initWithRootViewController:boatTypeVC];
  popVC.cornerRadius = 10;
  [popVC presentInViewController:self];
  
  @weakify(self)
  [boatTypeVC returnReturnPackageOrBoatType:^(NSString *type) {
    @strongify(self)
    self.boatTypeLF.contentField.text = type;
  }];
}

- (void)selectBoatImage{
  @weakify(self);
  UIAlertController *sheet = [UIAlertController alertControllerWithTitle:@"更换头像" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  sheet.title = nil;
  UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
  if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  }
  
  UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
    @strongify(self)
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
    picker.delegate = self;
    picker.allowsEditing = YES;//设置可编辑
    picker.sourceType = sourceType;
    [self presentViewController:picker animated:YES completion:nil];//进入照相界面
  }];
  UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"本地获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    @strongify(self)
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
    picker.delegate = self;
    picker.allowsEditing = YES;//设置可编辑
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:picker animated:YES completion:nil];//进入照相界面
  }];
  
  UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
  
  [sheet addAction:action1];
  [sheet addAction:action2];
  [sheet addAction:action3];
  
  [self presentViewController:sheet animated:YES completion:nil];
}

- (void)confirmAddBoat{
  NSString *boatname = self.boatNameLF.contentField.text;
  NSString *boattype = self.boatTypeLF.contentField.text;
  NSString *mmsi = self.mmsiLF.contentField.text;
  NSString *weight = self.weightLF.contentField.text;
  NSString *width = self.widthLF.contentField.text;
  NSString *draft = self.draftLF.contentField.text;
  NSString *boatlong = self.longLF.contentField.text;
  NSString *note = self.noteLF.contentField.text;
  NSData *imgData = UIImageJPEGRepresentation([self scaleToSize:self.addImageBtn.currentImage size:CGSizeMake(86, 86)], 0.1);
  
  
  
  if (boatlong.length > 0 && boatname.length > 0 && boattype.length > 0 && mmsi.length > 0 && weight.length > 0 && width.length > 0 && draft.length > 0 &&(self.fontBtn.selected || self.beforBtn.selected)) {
    
    NSString *cockpit = self.fontBtn.selected ? @"1" : @"0";
    NSDictionary *dic = @{@"shiponwerId":[DEFAULTS objectForKey:@"loginInformation"][@"id"],
                          @"boatname" : boatname,
                          @"mmsi":mmsi,
                          @"boattype":boattype,
                          @"loads":weight,
                          @"draft":draft,
                          @"height":boatlong,
                          @"weight":width,
                          @"note":note,
                          @"cockpit":cockpit};
    
    NSString *json = [dic mj_JSONString];
    NSString *posturl = [NSString backUrlWithService:@"boat" methodName:@"modifyboat"];

    @weakify(self)
    
    NSDictionary *parameters = @{@"boatjson":json,@"image":imgData};
    [SLNetWork uploadFileWithFileArr:@[json,imgData] andFileInformationArr:@[@"boatjson",@"image"] andPostUrl:posturl andParameters:parameters complete:^(id respond, NSError *error) {
      
      @strongify(self)
      [self.navigationController popViewControllerAnimated:YES];
    }];
    
  }else{
    [SVProgressHUD showErrorWithStatus:@"请完善信息"];
  }
  
  
}


#pragma mark - 照相机代理方法
//点击相册中的图片 货照相机照完后点击use  后触发的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
  @weakify(self);
  [picker dismissViewControllerAnimated:YES completion:^{
    @strongify(self)
    // 上传照片
    UIImage *icon = info[UIImagePickerControllerOriginalImage];
    UIImage *iconImage = [self scaleToSize:icon size:CGSizeMake(86, 86)];
    [self.addImageBtn setImage:icon forState:UIControlStateNormal];
    NSData *imgData = UIImageJPEGRepresentation(iconImage, 0.1);
    [DEFAULTS setObject:imgData forKey:@"boatPhoto"];
    [DEFAULTS synchronize];
  }];
}



-(UIImage *)scaleToSize:(UIImage *)image size:(CGSize)size
{
  //创建一个bitmap的context
  //并把他设置成当前的context
  UIGraphicsBeginImageContext(size);
  //绘制图片的大小
  [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
  //从当前context中创建一个改变大小后的图片
  UIImage *endImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  
  return endImage;
}

- (void)driveBtnTap:(UIButton *)btn{
  if (btn != self.button) {
    self.button.selected = NO;
    self.button = btn;
  }
  self.button.selected = YES;
}


- (void)setUpUI{
  [self.view addSubview:self.mainScrollView];
  [self.view addSubview:self.confirmBtn];
  [self.mainScrollView addSubview:self.contentView];
  [self.contentView addSubview:self.boatNameLF];
  [self.contentView addSubview:self.mmsiLF];
  [self.contentView addSubview:self.boatTypeLF];
  [self.contentView addSubview:self.weightLF];
  [self.contentView addSubview:self.draftLF];
  [self.contentView addSubview:self.longLF];
  [self.contentView addSubview:self.widthLF];
  [self.contentView addSubview:self.fontBtn];
  [self.contentView addSubview:self.beforBtn];
  [self.contentView addSubview:self.noteLF];
  [self.contentView addSubview:self.addView];
  UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"删除" style:UIBarButtonItemStylePlain target:self action:@selector(delectBoat)];
  self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)addConstrains{
  [self.mainScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.edges.equalTo(self.view);
  }];
  
  [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.edges.equalTo(self.mainScrollView);
    make.width.equalTo(self.mainScrollView);
  }];
  
  [self.boatNameLF mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.width.equalTo(self.view);
    make.height.equalTo(@(50*MIX_H));
    make.top.equalTo(self.contentView).offset(5);
  }];
  
  [self.mmsiLF mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.width.height.equalTo(self.boatNameLF);
    make.top.equalTo(self.boatNameLF.mas_bottom);
  }];
  
  [self.boatTypeLF mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.width.height.equalTo(self.mmsiLF);
    make.top.equalTo(self.mmsiLF.mas_bottom);
  }];
  
  UIImageView *typeimage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"v"]];
  [self.contentView addSubview:typeimage];
  [typeimage mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerY.equalTo(self.boatTypeLF);
    make.right.equalTo(self.contentView).offset(-10);
    make.size.mas_equalTo(CGSizeMake(15, 15));
  }];
  
  UIButton *typeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  [typeBtn addTarget:self action:@selector(selectBoatType) forControlEvents:UIControlEventTouchUpInside];
  [self.contentView addSubview:typeBtn];
  [typeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.top.width.equalTo(self.boatTypeLF.contentField);
    make.right.equalTo(typeimage);
  }];
  
  
  [self.weightLF mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.width.height.equalTo(self.boatTypeLF);
    make.top.equalTo(self.boatTypeLF.mas_bottom).offset(5);
  }];
  
  [self.draftLF mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.width.height.equalTo(self.weightLF);
    make.top.equalTo(self.weightLF.mas_bottom);
  }];
  
  [self.longLF mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.width.height.equalTo(self.draftLF);
    make.top.equalTo(self.draftLF.mas_bottom);
  }];
  
  [self.widthLF mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.width.height.equalTo(self.longLF);
    make.top.equalTo(self.longLF.mas_bottom);
  }];
  
  UILabel *label = [UILabel labelWithFontSize:16 textColor:[UIColor blackColor] text:@"驾驶室位置 :"];
  [self.contentView addSubview:label];
  [label mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(self.widthLF).offset(15);
    make.top.equalTo(self.widthLF.mas_bottom).offset(5);
  }];
  
  [self.fontBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerY.equalTo(label);
    make.left.equalTo(label.mas_right).offset(20);
    make.size.mas_equalTo(CGSizeMake(75, 25));
  }];
  
  [self.beforBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerY.equalTo(label);
    make.left.equalTo(self.fontBtn.mas_right).offset(20);
    make.size.mas_equalTo(CGSizeMake(75, 25));
  }];
  
  
  [self.noteLF mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.width.height.equalTo(self.widthLF);
    make.top.equalTo(self.fontBtn.mas_bottom).offset(5);
  }];
  
  [self.addView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.width.equalTo(self.noteLF);
    make.top.equalTo(self.noteLF.mas_bottom).offset(5);
    make.height.equalTo(@(120*MIX_W));
  }];
  
  [self setUpAddView];
  
  [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
    make.bottom.equalTo(self.addView).offset(70);
  }];
  
  
  
  [self.confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.bottom.width.equalTo(self.view);
    make.height.equalTo(@40);
  }];
  
}

- (void)setUpAddView{
  UILabel *label = [UILabel labelWithFontSize:16 textColor:SLInkColor text:@"船只图片"];
  [self.addView addSubview:label];
  [label mas_makeConstraints:^(MASConstraintMaker *make) {
    make.right.equalTo(self.addView.mas_left).offset(90*MIX_W);
    make.top.equalTo(self.addView).offset(8);
  }];
  
  [self.addView addSubview:self.addImageBtn];
  [self.addImageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(label.mas_bottom).offset(8);
    make.centerX.equalTo(self.addView);
    make.width.equalTo(self.addView).offset(-60);
    make.bottom.equalTo(self.addView).offset(-10);
  }];
  
}


- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
  
}


#pragma mark- getter

- (SLLabelFeild *)boatNameLF{
  if (!_boatNameLF) {
    _boatNameLF = [[SLLabelFeild alloc] initWithTitle:@"船舶名称" fieldPlaceHolder:@"请输入船舶名称"];
    _boatNameLF.limit = 8;
  }
  return _boatNameLF;
}

- (SLLabelFeild *)boatTypeLF{
  if (!_boatTypeLF) {
    _boatTypeLF = [[SLLabelFeild alloc] initWithTitle:@"船舶类型" fieldPlaceHolder:@"请输入船舶类型"];
  }
  return _boatTypeLF;
}

- (SLLabelFeild *)mmsiLF{
  if (!_mmsiLF) {
    _mmsiLF = [[SLLabelFeild alloc] initWithTitle:@"MMSI(呼号)" fieldPlaceHolder:@"请输入船只MMSI"];
    _mmsiLF.contentField.keyboardType = UIKeyboardTypePhonePad;
  }
  return _mmsiLF;
}

- (SLLabelFeild *)weightLF{
  if (!_weightLF) {
    _weightLF = [[SLLabelFeild alloc] initWithTitle:@"载重(吨)" fieldPlaceHolder:@"请输入船只载重"];
    _weightLF.contentField.keyboardType = UIKeyboardTypePhonePad;
  }
  return _weightLF;
}

- (SLLabelFeild *)draftLF{
  if (!_draftLF) {
    _draftLF = [[SLLabelFeild alloc] initWithTitle:@"吃水(米)" fieldPlaceHolder:@"请输入船只吃水"];
    _draftLF.contentField.keyboardType = UIKeyboardTypePhonePad;
  }
  return _draftLF;
}



- (SLLabelFeild *)widthLF{
  if (!_widthLF) {
    _widthLF = [[SLLabelFeild alloc] initWithTitle:@"船宽(米)" fieldPlaceHolder:@"请输入船只宽度"];
    _widthLF.contentField.keyboardType = UIKeyboardTypePhonePad;
  }
  return _widthLF;
}

- (SLLabelFeild *)longLF{
  if (!_longLF) {
    _longLF = [[SLLabelFeild alloc] initWithTitle:@"船长(米)" fieldPlaceHolder:@"请输入船只长度"];
    _longLF.contentField.keyboardType = UIKeyboardTypePhonePad;
  }
  return _longLF;
}

- (SLLabelFeild *)noteLF{
  if (!_noteLF) {
    _noteLF = [[SLLabelFeild alloc] initWithTitle:@"其它备注" textViewHolder:@"   "];
    _noteLF.limit = 200;
  }
  return _noteLF;
}

- (UIButton *)addImageBtn{
  if (!_addImageBtn) {
    _addImageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_addImageBtn setImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
    _addImageBtn.backgroundColor = SLInkColor;
    [_addImageBtn addTarget:self action:@selector(selectBoatImage) forControlEvents:UIControlEventTouchUpInside];
  }
  return _addImageBtn;
}

- (UIButton *)confirmBtn{
  if (!_confirmBtn) {
    _confirmBtn = [UIButton buttonWithTitle:@"保存"];
    _confirmBtn.backgroundColor = SLYellowColor;
    [_confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_confirmBtn addTarget:self action:@selector(confirmAddBoat) forControlEvents:UIControlEventTouchUpInside];
  }
  return _confirmBtn;
}

- (UIButton *)fontBtn{
  if (!_fontBtn) {
    _fontBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_fontBtn setImage:[UIImage imageNamed:@"Not checked"] forState:UIControlStateNormal];
    [_fontBtn setImage:[UIImage imageNamed:@"Check"] forState:UIControlStateSelected];
    [_fontBtn setTitle:@"前置" forState:UIControlStateNormal];
    [_fontBtn dw_imageTitleHorizontalAlignmentWithSpace:5];
    [_fontBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_fontBtn addTarget:self action:@selector(driveBtnTap:) forControlEvents:UIControlEventTouchUpInside];
    _fontBtn.tag = 100;
  }
  return _fontBtn;
}

- (UIButton *)beforBtn{
  if (!_beforBtn) {
    _beforBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_beforBtn setImage:[UIImage imageNamed:@"Not checked"] forState:UIControlStateNormal];
    [_beforBtn setImage:[UIImage imageNamed:@"Check"] forState:UIControlStateSelected];
    [_beforBtn setTitle:@"后置" forState:UIControlStateNormal];
    [_beforBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_beforBtn dw_imageTitleHorizontalAlignmentWithSpace:5];
    [_beforBtn addTarget:self action:@selector(driveBtnTap:) forControlEvents:UIControlEventTouchUpInside];
    _beforBtn.tag = 200;
  }
  return _beforBtn;
}


- (UIView *)contentView{
  if (!_contentView) {
    _contentView = [UIView new];
    _contentView.backgroundColor = [UIColor defeutBackgroudColor];
    
  }
  return _contentView;
}

- (UIScrollView *)mainScrollView{
  if (!_mainScrollView) {
    _mainScrollView = [UIScrollView new];
    _mainScrollView.backgroundColor = [UIColor defeutBackgroudColor];
  }
  return _mainScrollView;
}

- (UIView *)addView{
  if (!_addView) {
    _addView = [UIView new];
    _addView.backgroundColor = [UIColor whiteColor];
  }
  return _addView;
}



@end
